package com.dfdchem.imd.kaiwu.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.PopupMenu;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.manager.IntranetManager;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;

import java.util.Map;

/**
 * 用户嵌入OA新闻的专用Activity
 */
@Route(path = RouterPath.NEWS_OA_ACTIVITY)
public class NewsOAActivity extends BaseActivity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

    private static final String TAG = "NewsOAActivity";

    @Autowired
    String title;

    @Autowired
    boolean full_screen = false;

    private static String host = "http://oa.dfdchem.com:51151";
    private String start_url = host;
    private String oa_home_url = host + "/spa/coms/static4mobile/index.html#/menu-preview?id=appDefaultPage&checkAccess=1";
    private String news_home_url = host + "/spa/document/static4mobile/index.html#/news/11?moduleid=11";

    private TextView mTitleTextView;
    private AgentWeb mAgentWeb;
    private AgentWeb.PreAgentWeb preAgentWeb;
    private LinearLayout mLinearLayout;
    private View iv_back;
    private View iv_close;
    private View view_line;
    private View iv_more;
    private View webview_tool_bar;

    private PopupMenu mPopupMenu;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, NewsOAActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_oa);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        mTitleTextView = findView(R.id.web_view_toolbar_title);
        mLinearLayout = findView(R.id.webView_layout);
        webview_tool_bar = findView(R.id.webview_tool_bar);
        iv_back = findView(R.id.iv_back);
        iv_close = findView(R.id.iv_close);
        iv_more = findView(R.id.iv_more);
        view_line = findView(R.id.view_line);

        iv_close.setVisibility(View.GONE);
        view_line.setVisibility(View.GONE);
    }

    /**
     * 显示更多菜单
     *
     * @param view 菜单依附在该View下面
     */
    private void showPoPup(View view) {
        if (mPopupMenu == null) {
            mPopupMenu = new PopupMenu(this.getActivity(), view);
            mPopupMenu.inflate(R.menu.webview_toolbar_menu);
            mPopupMenu.setOnMenuItemClickListener(this);
        }
        mPopupMenu.show();
    }

    @Override
    public void initData() {
        mTitleTextView.setText("新闻公告");

        if (preAgentWeb == null) {
            preAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                    .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                    .createAgentWeb()
                    .ready();

        }
        mAgentWeb = preAgentWeb.get();
        mAgentWeb.getUrlLoader().loadUrl(start_url);
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            WebResourceRequest newRequest = new WebResourceRequest() {
                @Override
                public Uri getUrl() {
                    String url = request.getUrl().toString();
                    // 登录后进入主页时，替换为新闻链接
                    if (url.equals(oa_home_url)) {
                        url = news_home_url;
                        mAgentWeb.getUrlLoader().stopLoading();
                        mAgentWeb.getUrlLoader().loadUrl(news_home_url);
                    }
                    return Uri.parse(IntranetManager.convert(url));
                }

                @Override
                public boolean isForMainFrame() {
                    return request.isForMainFrame();
                }

                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public boolean isRedirect() {
                    return request.isRedirect();
                }

                @Override
                public boolean hasGesture() {
                    return request.hasGesture();
                }

                @Override
                public String getMethod() {
                    return request.getMethod();
                }

                @Override
                public Map<String, String> getRequestHeaders() {
                    return request.getRequestHeaders();
                }
            };
            return super.shouldOverrideUrlLoading(view, newRequest);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mAgentWeb.getJsAccessEntrace().quickCallJs("callJS");
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }
    };

    @Override
    public void initEvent() {
        iv_more.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_more:
                showPoPup(v);
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onReturnClick(View v) {
        finish();
    }

    @Override
    public void onBackPressed() {
        String currentUrl = mAgentWeb.getWebCreator().getWebView().getUrl();
        if (currentUrl.equals(news_home_url)) {
            super.onBackPressed();
            return;
        }
        if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.back();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.refresh:
                if (mAgentWeb != null) {
                    mAgentWeb.getUrlLoader().reload(); // 刷新
                }
                return true;

            case R.id.copy:
                if (mAgentWeb != null) {
                    toCopy(this, mAgentWeb.getWebCreator().getWebView().getUrl());
                    showShortToast("复制链接成功");
                }
                return true;
            case R.id.default_browser:
                if (mAgentWeb != null) {
                    openBrowser(mAgentWeb.getWebCreator().getWebView().getUrl());
                }
                return true;
            case R.id.default_clean:
                toCleanWebCache();
                return true;
            case R.id.error_website:
                loadErrorWebSite();
                return true;
            default:
                return false;
        }
    }

    /**
     * 复制字符串
     *
     * @param context
     * @param text
     */
    private void toCopy(Context context, String text) {
        ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (mClipboardManager != null) {
            mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
        }
    }

    /**
     * 打开浏览器
     *
     * @param targetUrl 外部浏览器打开的地址
     */
    private void openBrowser(String targetUrl) {
        if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://") || targetUrl.startsWith("kaiwu://")) {
            Toast.makeText(this, targetUrl + " 该链接无法使用浏览器打开。", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri mUri = Uri.parse(targetUrl);
        intent.setData(mUri);
        startActivity(intent);
    }

    /**
     * 测试错误页的显示
     */
    private void loadErrorWebSite() {
        if (mAgentWeb != null) {
            mAgentWeb.getUrlLoader().loadUrl("http://www.unkownwebsiteblog.me");
        }
    }

    /**
     * 清除 WebView 缓存
     */
    private void toCleanWebCache() {
        if (this.mAgentWeb != null) {
            //清理所有跟WebView相关的缓存 ，数据库， 历史记录 等。
            this.mAgentWeb.clearWebCache();
            Toast.makeText(getActivity(), "已清理缓存", Toast.LENGTH_SHORT).show();
            //清空所有 AgentWeb 硬盘缓存，包括 WebView 的缓存 , AgentWeb 下载的图片 ，视频 ，apk 等文件。
            AgentWebConfig.clearDiskCache(this);
        }

    }
}
